package com.laiketui.plugin.common.service;

import com.laiketui.plugin.common.domain.base.coupon.CouponModal;
import com.laiketui.plugin.common.domain.base.coupon.CouponOrderModal;
import com.laiketui.plugin.common.domain.exception.LaiKeAPIException;
import com.laiketui.plugin.common.interfaces.PublicCouponService;
import com.laiketui.plugin.common.mapper.CouponModalMapper;
import com.laiketui.plugin.common.mapper.CouponOrderModalMapper;
import com.laiketui.plugin.common.tool.SplitUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;


/**
 * 优惠卷公共流程
 *
 * @author Trick
 * @date 2020/10/30 15:00
 */
@Service
public class PublicCouponServiceImpl implements PublicCouponService {
    private final Logger logger = LoggerFactory.getLogger(PublicCouponServiceImpl.class);

    @Autowired
    private CouponModalMapper couponModalMapper;

    @Autowired
    private CouponOrderModalMapper couponOrderModalMapper;

    /**
     * 更新优惠券状态 返回0失败1成功 coupon-update_coupon
     *
     * @param storeId
     * @param userId
     * @param couponIds
     * @param type
     * @return
     */
    @Override
    public int updateCoupons(int storeId, String userId, String couponIds, int type) {
        try {
            // 优惠券ID数组
            String[] couponIdList = couponIds.split(SplitUtils.DH);
            for (String couponIdStr : couponIdList) {
                int couponId = Integer.parseInt(couponIdStr);
                if (couponId != 0) {
                    int row = couponModalMapper.updateCoupon(type, storeId, userId, couponId);
                    if (row < 0) {
                        return 0;
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return 0;
        }
        return 1;
    }

    /**
     * 优惠券关联订单 返回0 表示关联失败 1 表示成功 添加关联订单信息 ： coupon_sno
     *
     * @param storeId
     * @param userId
     * @param couponIds
     * @param sNo
     * @param type
     * @return
     */
    @Override
    public int couponWithOrder(int storeId, String userId, String couponIds, String sNo, String type) {
        try {
            // 优惠券ID数组
            String[] couponIdsArray = couponIds.split(SplitUtils.DH);
            for (String couponIdStr : couponIdsArray) {
                int couponId = Integer.parseInt(couponIdStr);
                if (couponId != 0) {
                    if ("add".equals(type)) {
                        CouponOrderModal couponOrderModal = new CouponOrderModal();
                        couponOrderModal.setStore_id(storeId);
                        couponOrderModal.setUser_id(userId);
                        couponOrderModal.setCoupon_id(couponId);
                        couponOrderModal.setsNo(sNo);
                        couponOrderModal.setRecycle(0);
                        couponOrderModal.setAdd_date(new Date());
                        int arow = couponOrderModalMapper.insertSelective(couponOrderModal);
                        if (arow <= 0) {
                            return 0;
                        }
                    } else {
                        int r0 = couponOrderModalMapper.updateCouponOrder(storeId, userId, couponId);
                        if (r0 <= 0) {
                            return 0;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("优惠券关联订单 异常", e);
            return 0;
        }
        return 1;
    }


    /**
     * 返回用户可以使用的会员优惠券
     *
     * @param storeId
     * @param userId
     * @param amount
     * @return
     * @throws LaiKeAPIException
     */
    @Override
    public List<Map<String, Object>> getUserCoupon(int storeId, String userId, BigDecimal amount) throws LaiKeAPIException {
        List<Map<String, Object>> resultMap = new ArrayList<>();
        try {
            List<Map<String, Object>> userCoupon = couponModalMapper.getUserCoupon(storeId, userId);
            userCoupon.stream().forEach(coupon -> {
                //优惠券类型 1=免邮 2=满减 3=折扣 4=会员赠送
                Integer activityType = MapUtils.getInteger(coupon, "activity_type");
                if (CouponModal.COUPON_TYPE_MJ.equals(activityType.toString()) || CouponModal.COUPON_TYPE_ZK.equals(activityType.toString())) {
                    //满减条件
                    String zMoney = MapUtils.getString(coupon, "z_money");
                    if (new BigDecimal(zMoney).compareTo(amount) <= 0) {
                        resultMap.add(coupon);
                    }
                } else {
                    resultMap.add(coupon);
                }
            });
            // 添加一条不使用优惠劵
            Map<String, Object> map = new HashMap<>();
            map.put("activity_type", 2);
            map.put("couponType", 4);
            map.put("grade_id", 0);
            map.put("hid", 0);
            map.put("id", 0);
            map.put("money", BigDecimal.ZERO);
            map.put("z_money", BigDecimal.ZERO);
            map.put("name", "不使用优惠券");
            map.put("user_id", userId);
            map.put("choose", true);
            resultMap.add(map);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return resultMap;
    }
}

